$(function(){
    // fn延时调用函数，delay延迟时间，atleast至少多长时间触发一次
    function throttle(fn, delay, atleast) {
        var timeout = null,
        startTime = new Date();
        console.log("1"+startTime);
        return function() {
            var curTime = new Date();
            console.log("2"+curTime);
            clearTimeout(timeout);
            if(curTime - startTime >= atleast) {
                fn();
                // lazyload();
                // console.log(lazyload());
                startTime = curTime;
            }else {
                timeout = setTimeout(fn, delay);
            }
        }
    }
    function lazyload() {
        var images = document.getElementsByTagName('img');
        var len   = images.length;
        //存储图片加载到的位置，避免每次都从第一张图片开始遍历
        var n  = 0;    
        return function() {
            // clientHeight 可视区域的高度
            var seeHeight = document.documentElement.clientHeight;
            // scrollTop 滚动条拉动的距离
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            for(var i = n; i < len; i++) {
                // console.log(1);
                // offsetTop 当前对象到顶部的距离
                if(images[i].offsetTop < seeHeight + scrollTop) {
                    if(images[i].getAttribute('src') === './image/loading.gif') {
                        images[i].src = images[i].getAttribute('data-src');
                    }
                    n = n + 1;
                    console.log(n);
                }
            }
        }
    }
    // console.log(lazyload());
    var loadImages = lazyload();
    loadImages();      //初始化首页的页面图片
    window.addEventListener('scroll', throttle(lazyload(), 500, 1000), false);
})
